//
//  EvidenceOfEventViewerViewController.m
//  SecretRoom
//
//  Created by Sitdhibhong Laokok on 9/5/54 BE.
//  Copyright 2554 App Tree. All rights reserved.
//

#import <ImageIO/ImageIO.h>

#import "EvidenceOfEventViewerViewController.h"
#import "ImageFullScreenViewController.h"

#import "SLCommonsSecretRoomMessageBuilder.h"

#import "EvidenceMeta.h"

#import "EXF.h"

#import "SLCommonsMapsDisplay.h"

@interface EvidenceOfEventViewerViewController ()
- (void)setupEvidenceFetchedResultController;
- (void)displayComposeSheetForSendEvidence;
- (void)displayComposeSheetForPoseEventToFacebook;
@end

@implementation EvidenceOfEventViewerViewController
@synthesize evidecePickerController = _evidecePickerController;
@synthesize evidenceImagePicker;
@synthesize cameraConnection;
@synthesize flexibleWidth;
@synthesize context;
@synthesize evidenceFetchedResultController=_evidenceFetchedResultController;
@synthesize event=_event;
@synthesize evidenceForThisEvent;
@synthesize locationPoint;
@synthesize locationManager=_locationManager;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        [self performSelectorInBackground:@selector(locationManager) withObject:nil];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = self.event.eventName;
        
    UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshForImageFromServer)];
    
    UIBarButtonItem *showImageListButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(showActionPerformed)];
    
//    self.navigationItem.rightBarButtonItem = refreshButton;
    
    self.toolbarItems = [NSArray arrayWithObjects:self.cameraConnection, self.flexibleWidth, showImageListButton, nil];
    
    sourceTypeIsComesFromCamera = NO;
    
    [refreshButton release];
    [showImageListButton release];
}

- (void)viewDidUnload
{
    [self setCameraConnection:nil];
    [self setFlexibleWidth:nil];
    [self setEvidenceFetchedResultController:nil];
    [self setContext:nil];
    [self setEvent:nil];
    [self setEvidenceForThisEvent:nil];
    [self setEvidenceImagePicker:nil];
    [self setEvidecePickerController:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.toolbar.barStyle = UIBarStyleDefault;
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    
    NSError *error = nil;
    [self.evidenceFetchedResultController performFetch:&error];
    if (error != nil) {
        NSLog(@"Error while evidence fetching: %@", [error localizedDescription]);
    }
    
    [self.tableView reloadData];
    
//    NSLog(@"%s Message : %@", __PRETTY_FUNCTION__, [_evidenceFetchedResultController.sections count]);
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.view setBackgroundColor:[UIColor whiteColor]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES; // ( interfaceOrientation == (UIInterfaceOrientationPortrait|UIInterfaceOrientationLandscapeRight|UIInterfaceOrientationLandscapeLeft) );
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[[self.evidenceFetchedResultController sections] lastObject] numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.imageView.layer.cornerRadius = 10;
    }
    
    // Configure the cell...
    Evidence *ev = [self.evidenceFetchedResultController objectAtIndexPath:indexPath];
//    UIImage *thumnail = nil;
//    NSLog(@"Event: %@", self.event);
//    NSLog(@"%@", [SLCommonsFileUtility evidenceURLResolvedWithEvidence:ev inEvent:ev.belongToEvents]);
//    NSLog(@"belongToEvent: %@", ev.belongToEvents);
//    NSLog(@"Evidence: %@", ev);
//    if (ev.thumbnail == nil) {
//        thumnail = [UIImage imageWithContentsOfFile:[SLCommonsFileUtility evidenceURLResolvedWithEvidence:ev inEvent:ev.belongToEvents]];
//    } else {
//        thumnail = [UIImage imageWithData:ev.thumbnail];
//    }
//    
//    cell.imageView.image = thumnail;
    
    if (ev.evidenceName != nil) {
        cell.textLabel.text = [NSString stringWithFormat:@"%@", ev.evidenceName];
    } else {
        cell.textLabel.text = [NSString stringWithFormat:@"%@", ev.filename];
    }
    
    cell.imageView.frame = CGRectMake(0, 0, 44, 44);

    cell.imageView.layer.masksToBounds = YES;
        
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ImageFullScreenViewController *ifsvc = [[[ImageFullScreenViewController alloc] initWithEvidence:[self.evidenceFetchedResultController objectAtIndexPath:indexPath] forEvent:self.event] autorelease];
    
    [self.navigationController pushViewController:ifsvc animated:YES];
}

- (void)dealloc {
    [cameraConnection release];
    [flexibleWidth release];
    [evidenceFetchedResultController release];
    [context release];
    [event release];
    [evidenceForThisEvent release];
    [evidenceImagePicker release];
    [evidecePickerController release];
    
    [dateFormatter release];
    
    [super dealloc];
}

- (IBAction)cameraOpened:(id)sender 
{
    UIActionSheet *imageSourceTypeSelector = nil;
    
    imageSourceTypeSelector.tag = 100;
    
    NSInteger defaultSourceIsCamera =[[NSUserDefaults standardUserDefaults] integerForKey:kSRPreferenceDefaultImageSource];
    BOOL isCameraExists = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    if ((defaultSourceIsCamera == 1) && isCameraExists) {
        // set soure to camera, then present camera
        evidenceImagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentModalViewController:evidenceImagePicker animated:YES];
        
    } else if (defaultSourceIsCamera == 2) {
        // Default is Photo Library
        evidenceImagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:evidenceImagePicker animated:YES];
    } else {
        // let's user select source type by themself
        if (!isCameraExists) {
            evidenceImagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentModalViewController:evidenceImagePicker animated:YES];
            
        } else {
            imageSourceTypeSelector = [[UIActionSheet alloc] initWithTitle:@"Photo Source" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Camera", @"Photo Library", nil];
            [imageSourceTypeSelector showFromToolbar:self.navigationController.toolbar];
            [imageSourceTypeSelector release];
        }
        
    }
    
}

#pragma mark - Accessor Override
- (UIImagePickerController *)evidenceImagePicker
{
    if (_evidecePickerController != nil) {
        return _evidecePickerController;
    }
    
    _evidecePickerController = [[UIImagePickerController alloc] init];
    _evidecePickerController.delegate = self;
    _evidecePickerController.allowsEditing = NO;
    
    return _evidecePickerController;
}

#pragma mark - UIAlertView
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.cancelButtonIndex != buttonIndex) {
        // ok
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto:"]];
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 200) {
        // Share options
        switch (buttonIndex) {
            case 0:
                // share via e-mail
                [self displayComposeSheetForSendEvidence];
                break;
            case 1:
                // display upload page to facebook
                [self displayComposeSheetForPoseEventToFacebook];
                break;
        }
        
    } else {
        switch (buttonIndex) {
            case 0:
                // Camera
                evidenceImagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                sourceTypeIsComesFromCamera = YES;
                [self presentModalViewController:evidenceImagePicker animated:YES];
                break;
            
            case 1:
                // Photo Library
                evidenceImagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentModalViewController:evidenceImagePicker animated:YES];
                break;
        }
        
    }
    
    
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"%s Image information: %@", __PRETTY_FUNCTION__, info);
    [evidenceImagePicker dismissModalViewControllerAnimated:YES];
    
    UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    // Image saved and return save location
    NSError *e = nil;
    NSString *saveLocation = [FileRepositoryControlCenter saveImage:originalImage 
                                                           withType:kSaveImageFileTypeToJPG 
                                                    toSuffixLibrary:[SLCommonsFileUtility categoryFromEvent:self.event] 
                                                              error:&e];
    
//    CGFloat compressQuality = [[NSUserDefaults standardUserDefaults] integerForKey:kSRPreferenceImageQuantityLevel];    
//    EXFJpeg *jpegScanner = [[EXFJpeg alloc] init];
//    [jpegScanner scanImageData:rawImageData];
    
    NSLog(@"Image saved to location: %@", saveLocation);
    
    if (e != nil) {
        NSLog(@"%s Error while saving data : %@", __PRETTY_FUNCTION__, [e localizedDescription]);
    } else if (e == nil && [[NSFileManager defaultManager] fileExistsAtPath:saveLocation]) {
        
        NSLog(@"Context: %@", self.context);
        
        ////////
        Evidence *newEvidenceCollected = [[Evidence alloc] initWithEntity:[NSEntityDescription entityForName:@"Evidence" 
                                                                                      inManagedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext]] 
                                           insertIntoManagedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext]];
        
        NSDictionary *metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
        NSLog(@"Meta data: %@", metadata);
        
        NSDictionary *fileAttribute = [[NSFileManager defaultManager] attributesOfItemAtPath:saveLocation error:nil];
        
        NSDate *collectedData = [SLCommonsDateUtility localDateToGMTDate:[dateFormatter dateFromString:[[metadata objectForKey:@"{Exif}"] objectForKey:@"DateTimeOriginal"]]];
        
        NSLog(@"Cdat: %@", collectedData);
        
        newEvidenceCollected.datetimeCollected = collectedData == nil ? collectedData : [SLCommonsDateUtility currentGMTDate] ;
        newEvidenceCollected.filename = [[saveLocation lastPathComponent] stringByDeletingPathExtension];
        newEvidenceCollected.filesize = [NSNumber numberWithLong:(long)[fileAttribute objectForKey:NSFileSize]];
        newEvidenceCollected.height = [NSNumber numberWithFloat:originalImage.size.height];
        newEvidenceCollected.width = [NSNumber numberWithFloat:originalImage.size.width];
        newEvidenceCollected.isSynced = [NSNumber numberWithBool:NO];
        newEvidenceCollected.localUrl = [saveLocation stringByReplacingOccurrencesOfString:[SLCommonsFileUtility shortHandForDocumentPath] withString:@""];
        newEvidenceCollected.belongToEvents = self.event;
        
        EvidenceMeta *evidenceMeta = [[EvidenceMeta alloc] initWithEntity:[NSEntityDescription entityForName:@"EvidenceMeta" inManagedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext]] insertIntoManagedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext]];
        
        evidenceMeta.metaName = kSRImageMetadataHash;
        evidenceMeta.metaValue = [[NSData dataWithContentsOfFile:saveLocation] MD5];
        
        newEvidenceCollected.metadatas = [NSSet setWithObjects:evidenceMeta, nil];
        
        NSLog(@"MD5 : %@", [[NSData dataWithContentsOfFile:saveLocation] MD5]);
        
        if (self.event.keyImage == nil) {
            self.event.keyImage = newEvidenceCollected.localUrl;
        }
        
        NSError *saveerror = nil;
        [[[SRConnectionControlCenter sharedInstance] manageObjectContext] save:&saveerror];
        
        if (saveerror != nil) {
            NSLog(@"%s Error while saving evidence: %@", __PRETTY_FUNCTION__, [e localizedDescription]);
        }
        
        NSLog(@"EVDFSDLFJKSD:LFSDKJF : %@", newEvidenceCollected);
        
        [self.evidenceFetchedResultController performFetch:nil];
        [self.tableView reloadData];
        
        [newEvidenceCollected release];
        [evidenceMeta release];
    }
    
    sourceTypeIsComesFromCamera = NO;

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    NSLog(@"%s - ", __PRETTY_FUNCTION__);
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"Cancel");
    sourceTypeIsComesFromCamera = NO;
    [picker dismissModalViewControllerAnimated:YES];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    
}

#pragma mark - Accessor override
- (CLLocationManager *)locationManager
{
    if (_locationManager != nil) {
        return _locationManager;
    }
    
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    return _locationManager;
}

- (void)setEvent:(Event *)e 
{
    if (_event != e) {
        [_event release];
        _event = [e retain];
    }
    
    [self setupEvidenceFetchedResultController];
}

#pragma mark - Private Method
- (void)setupEvidenceFetchedResultController
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Evidence" 
                                 inManagedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext]];
    
    request.predicate = [NSPredicate predicateWithFormat:@"belongToEvents = %@", self.event];
    
    NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"datetimeCollected" ascending:NO];
    
    request.sortDescriptors = [NSArray arrayWithObjects:sortByDate, nil];
    
    NSFetchedResultsController *fetchedRequest = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext] sectionNameKeyPath:nil cacheName:nil];
    fetchedRequest.delegate = self;
    
    self.evidenceFetchedResultController = fetchedRequest;
    
    [fetchedRequest release];
    [request release];
    
    NSError *e = nil;
    [self.evidenceFetchedResultController performFetch:&e];
    
    if (e != nil) {
        NSLog(@"Error while fetching: %@", [e localizedDescription]);
    } 
}

#pragma mark - Swipe for Delete
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Delete some at indexPath: %@", indexPath);
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        Evidence *deleteEvidence = [self.evidenceFetchedResultController objectAtIndexPath:indexPath];
        [[[SRConnectionControlCenter sharedInstance] manageObjectContext] deleteObject:deleteEvidence];
        
        NSError *error = nil;
        [[[SRConnectionControlCenter sharedInstance] manageObjectContext] save:&error];
        if (error != nil) {
            NSLog(@"%s Error while saving deleted row entity: %@", __PRETTY_FUNCTION__, [error localizedDescription]);
        }
    }
}

#pragma mark - Implemented method
- (void)refreshForImageFromServer
{
    
}

- (void)showActionPerformed
{
    UIActionSheet *shareOptions = [[UIActionSheet alloc] initWithTitle:@"Share" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"E-mail", nil];
    
    shareOptions.tag = 200;
    
    [shareOptions showFromToolbar:self.navigationController.toolbar];
    [shareOptions release];
}

#pragma mark - NSFetchedResultController
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView reloadData];
}

#pragma mark - MessageUI display compose sheet
- (void)displayComposeSheetForSendEvidence
{
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *evidenceSendComposer = [[MFMailComposeViewController alloc] init];
        evidenceSendComposer.mailComposeDelegate = self;
        
        [evidenceSendComposer setSubject:[NSString stringWithFormat:@"%@", self.event.eventName]];
        
        SLCommonsSecretRoomMessageBuilder *messageBuilder = [[SLCommonsSecretRoomMessageBuilder alloc] initWithEvent:self.event];
        
        [evidenceSendComposer setMessageBody:[messageBuilder messageBody] isHTML:YES];
        
        for (Evidence *evd in [[[self.evidenceFetchedResultController sections] lastObject] objects]) {
            UIImage *image = [UIImage imageWithContentsOfFile:[SLCommonsFileUtility evidenceURLResolvedWithEvidence:evd inEvent:self.event]];
            NSData *imageData = UIImageJPEGRepresentation(image, [[NSUserDefaults standardUserDefaults] floatForKey:kSRPreferenceImageQuantityLevel]);
            
            [evidenceSendComposer addAttachmentData:imageData mimeType:@"image/jpg" fileName:[evd.filename lastPathComponent]];
            
        }
        
        [self presentModalViewController:evidenceSendComposer animated:YES];

        [evidenceForThisEvent release];
        [messageBuilder release];
    } else {
        UIAlertView *mailConfigAlert = [[UIAlertView alloc] initWithTitle:nil message:@"Can't send e-mail right now, please config e-mail first." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        [mailConfigAlert show];
        [mailConfigAlert release];
    }
    
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [self dismissModalViewControllerAnimated:YES];
}

- (void)displayComposeSheetForPoseEventToFacebook
{
    
}

@end
